<template>
  <el-dialog @close="onClose" :title="title" :visible.sync="visible">
    <el-upload
      class="upload-demo"
      drag
      :data="formData"
      ref="upload"
      :action="realAction"
      :auto-upload="false"
      :file-list="fileList"
      :on-success="onSuccess"
      :on-error="onError"
      multiple>
      <i class="el-icon-upload"></i>
      <div class="el-upload__text">
        <p><em>点击上传</em>或将文件拖拽到此处上传</p>
        <p>
        <span>仅支持xls、xlsx格式文件</span>
        <span style="color: #333333;" @click.stop="downloadTemp">&nbsp;&nbsp;  <i class="el-icon-download"></i>
          模板下载
        </span>
        </p>
      </div>
    </el-upload>
    <el-button style="margin-left: 10px;" size="small" type="primary" @click="submitUpload">确定</el-button>
    <el-button style="margin-left: 10px;" size="small"  @click="onClose">取消</el-button>

  </el-dialog>
</template>

<script>
import {Message} from 'element-ui'
import requestConfig from '../api/config'
import Cookies from 'js-cookie'
export default {
  props: {
    action: {
      type: String,
      default: '/user/batch/create/'
    },
    title: {
      type: String,
      default: '导入用户'
    },
    show: {
      type: Boolean,
      default: false
    },
    type: {
      type: [Number, String],
      default: 1
    },
    temp: {
      type: [Number, String],
      default: 1
    }
  },
  data() {
    return {
      visible: false,
      fileList: []
    }
  },
  computed: {
    formData() {
      return {
        type: this.type
      }
    },
    realAction() {
      return requestConfig[process.env.NODE_ENV].api + this.action;
    }
  },
  watch: {
    show() {
      this.visible = this.show
    },
  },
  methods: {
    onClose() {
      this.$emit('onClose')
    },
    downloadTemp() {
      let tempFile = [
        '教师批量导入模板.xlsx',
        '教师批量导入模板.xlsx', // 1
        '学生批量导入模板.xlsx', // 2
        '专家批量导入模板.xlsx', // 3
        '学生批量选课导入模板.xlsx', // 4
        '教师批量授课导入模板.xlsx', // 5
        '班级学生批量导入模板.xlsx', // 6
        '班级批量导入模板.xlsx', // 7
        '课程批量导入模板.xlsx', // 8
        '学校批量导入模板.xlsx', // 9
        '学院批量导入模板.xlsx', // 10
        '专业批量导入模板.xlsx', // 11
        '课程批量导入模板.xlsx', // 12
        '选择题批量导入模板.xlsx', // 13
        '简答题批量导入模板.xlsx', // 14
      ][parseInt(this.temp)];
      let el = document.createElement('a');
      el.href = '/templates/' + tempFile;
      el.click();
    },
    submitUpload() {
      console.log(this.$refs.upload.uploadFiles)
      this.$refs.upload.headers['X-CSRFToken'] = Cookies.get('csrftoken');
      this.$refs.upload.submit();
    },
    onSuccess (resp, file, fileList) {
      console.log(resp, file, fileList);
      if(resp.error_code == 0) {
        Message.success(resp.message);
        this.onClose();
      }else{
        Message.error(resp.message);
      }
    },
    onError(err) {
      console.error(err);
      Message.error('上传失败');
    }
  }
}
</script>

<style>

</style>